<?php

class Model_Points extends Model {

    function __construct() {
        
    }

    /**
     * controller調用此function進行加減分操作
     * @param    $action 操作名
     * @param    $remark 備註
     * @param    $uid 用戶id
     * @param    $oid 對應要凍結積分的產品/活動ID
     * @param    $points_freeze 要凍結的積分
     * @return   array
     */
    function points_record($uid, $action, $remark = "", $oid = 0, $points_freeze = 0) {
        
        $true = 0;
        $result = array('ret' => 0);
        //if (empty($_COOKIE["points_record_one"])) {
        // setcookie("points_record_one", 1, time() + 1);
        if (!$uid || !$action) {
            $result = array('ret' => 0, 'reason' => '用戶id或action不能為空');
        } else {
            
            //if($action=='reg') sos("1 uid: ".$uid);
            //今日獲取的分數
            $today_add_points = $this->get_today_points($uid, $action, 1);

            
            //獲得該action對應加or減的分數
            $points_array = $this->get_points_action($action);
            
            if ($points_array)
                $points_array = $points_array[0];

            $is_add_str = $points_array['is_add'] ? ' 加' : ' 減';
            $limit_points_str = ($points_array['limit_points'] > 0) ? ' 每日加分上限：' . $points_array['limit_points'] . '分' : ' 加分無上限';
            $action_name = $points_array['name'] . $is_add_str . '分' . $points_array['points'] . $limit_points_str;

            if ($points_array['limit_points'] > 0 && $points_array['limit_points'] <= count($today_add_points)) {
                //加分大於每日上限
                $result = array('ret' => 0, 'reason' => '加分大於每日上限', 'action' => $action_name);
            } else {

                //查詢可用的分數
                $data_points_detail = $this->get_points($uid);
                
                //if($action=='reg') sos("2 uid: ".$uid);
                //如果有剩餘分數 或者 是加分操作 或者是與凍結積分相關操作
                if ($data_points_detail || $points_array['is_add'] == 1 && !$data_points_detail || intval($points_freeze) > 0) {
                    
                    //如果有凍結分數數字，就扣凍結分數數字
                    $points = (intval($points_freeze) > 0) ? intval($points_freeze) : $points_array['points'];

                    
                    $ret = $this->operate_points($data_points_detail, $points, $points_array['is_add'], $uid, $action, $oid);
                    
                    if ($ret) {
                        //if($action=='reg') sos("3 uid: ".$uid);

                        if ($ret['is_points_freeze'] == 0 && ($action == "confirm_product_invite" || $action == "confirm_event_invite")) {
                            $remark = str_replace("凍結", "非凍結", $remark);
                        }
                        if ($ret['not_enough_points'] == 1) {
                            $remark = $remark . '[分數不夠扣到0分]';
                        }
                        //更新分數和加減分記錄
                        $this->update_points($uid, $points_freeze, $action, $ret['operate_points'], $points_array['is_add'], $remark);
                        
                        $true = 1;
                    } else {
                        $result = array('ret' => 0, 'reason' => '分數不夠扣減', 'action' => $action_name);
                        
                    }
                } else {
                    $result = array('ret' => 0, 'reason' => '沒有分數可以扣減', 'action' => $action_name);
                    
                }
            }
        }

        // }
        
        return $true ? array('ret' => 1, 'point' => $ret['operate_points'], 'is_add' => $points_array['is_add'], 'action' => $action_name) : $result;
    }

    /**
     * 更新分數和加減分記錄
     * @return   array
     */
    function update_points($uid, $points_freeze, $action, $points, $is_add, $remark) {

        $points_new_arr = $this->get_points($uid);
        $update_arr = array();
        if ($points_new_arr) {
            $total_points = 0;
            foreach ($points_new_arr as $value) {
                $total_points = $total_points + $value['surplus_points'];
            }

            $update_arr['points'] = $total_points;
        } else {

            $update_arr['points'] = 0;
        }

        //如果與凍結積分相關操作
        if (intval($points_freeze) > 0) {
            $get_all_points_freeze = $this->get_points_freeze($uid);

            if ($get_all_points_freeze) {
                $total_points_freeze = 0;
                foreach ($get_all_points_freeze as $value) {
                    $total_points_freeze = $total_points_freeze + $value['points'];
                }

                $update_arr['points_freeze'] = $total_points_freeze;
            } else {
                $update_arr['points_freeze'] = 0;
            }
        }

        db_update('member_imore', $update_arr, 'id=' . mysql_escape_string($uid));

        //添加加減分記錄
        $attr = array();
        $attr['uid'] = $uid;
        $attr['addtime'] = date('Y-m-d H:i:s');
        $attr['action'] = $action;
        $attr['points'] = $points;
        $attr['is_add'] = $is_add;
        $attr['remark'] = $remark;
        db_add('points_record', $attr);


        return true;
    }

    /**
     * 解凍積分
     * @return   array
     */
    function unfreeze_points($action, $uid, $oid, $points) {
        //解凍積分
        $is_add_points = 1;
        if ($action == "unfreeze_product_invite") {
            $points_unfreeze_product = db_query_one('points_freeze', array('field' => '', 'where' => 'uid=' . $uid . ' and status=1 and product_id=' . $oid));
            if ($points_unfreeze_product['result']) {
                $sql = 'update points_freeze set  status=0 ,last_points=-' . mysql_escape_string($points) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where uid=' . mysql_escape_string($uid) . ' and product_id=' . $oid;
                db_handle($sql);
            } else {
                $is_add_points = 0;
            }
        } elseif ($action == "unfreeze_event_invite") {
            $points_unfreeze_product = db_query_one('points_freeze', array('field' => '', 'where' => 'uid=' . $uid . ' and status=1 and event_id=' . $oid));
            if ($points_unfreeze_product['result']) {
                $sql = 'update points_freeze set  status=0 ,last_points=-' . mysql_escape_string($points) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where uid=' . mysql_escape_string($uid) . ' and event_id=' . $oid;
                db_handle($sql);
            } else {
                $is_add_points = 0;
            }
        }
        return $is_add_points ? true : false;
    }

    /**
     * 操作積分加或減
     * @param    $add :1加分，0減分，2全部
     * @param    $points 分數
     * @param    $uid 用戶id
     * @param    $points_array 剩餘分數
     * @return   array
     */
    function operate_points($points_array, $points, $is_add, $uid, $action, $oid = 0) {

        $deduct_array = array('lost_product', 'no_report', 'reject_report', 'delay_report', 'miss_activity', 'system_deduction');

        $true = 0;
        $not_enough_points = 0;
        $operate_points = $points;
        $is_points_freeze = 0;

        $points_freeze = $points;
        if ($is_add == 1) {
            //加分操作

            $is_add_points = 1;
            //解凍積分
            if ($action == "unfreeze_product_invite" || $action == "unfreeze_event_invite") {
                $ret = $this->unfreeze_points($action, $uid, $oid, $points);
                $is_add_points = $ret ? 1 : 0;
            }

            if ($is_add_points) {
                $points_detail_result = db_query_one('points_detail', array('field' => '', 'where' => 'uid=' . $uid . ' and settlement_time="' . date('Y-m-1 00:00:00') . '"'));
                if ($points_detail_result['result']) {
                    db_handle('update points_detail set total_points=total_points+' . mysql_escape_string($points) . ',surplus_points=surplus_points+' . mysql_escape_string($points) . ',last_points=' . mysql_escape_string($points) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where uid=' . mysql_escape_string($uid) . ' and settlement_time="' . date('Y-m-1 00:00:00') . '"');
                } else {
                    $attr = array();
                    $attr['uid'] = $uid;
                    $attr['settlement_time'] = date('Y-m-01 00:00:00');
                    $attr['total_points'] = $points;
                    $attr['surplus_points'] = $points;
                    $attr['expiration_time'] = $this->expiration_month();
                    db_add('points_detail', $attr);
                }

                $true = 1;
            }
        } else {
            //減分操作
            if ($points_array) {
                $is_points_freeze = 0;

                if (($action == "confirm_product_invite" || $action == "confirm_event_invite") && $oid) {
                    $get_points_freeze = $this->get_points_freeze($uid, $oid, $action);

                    $user_points_freeze = $get_points_freeze ? $get_points_freeze[0]['points'] : 0;

                    if ($user_points_freeze == $points) {
                        $is_points_freeze = 1;
                    }
                }
                
                //是否減凍結積分
                if ($is_points_freeze) {
                    if ($get_points_freeze) {
                        $sql = 'update points_freeze set  status=0 ,last_points=-' . mysql_escape_string($points) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where id=' . mysql_escape_string($get_points_freeze[0]['id']);
                        
                        db_handle($sql);
                    }
                   
                    $true = 1;
                } else {
                    
                    $total_points = 0;
                    foreach ($points_array as $value) {
                        $total_points = $total_points + $value['surplus_points'];
                    }
                    if ($total_points >= $points) {

                        $result_points = $this->deduct_points($points_array, $points);
                        if ($result_points)
                            $true = 1;

                        if ($action == "submit_product_invite") {

                            $insert_data = array();
                            $insert_data['uid'] = $uid;
                            $insert_data['points'] = $points_freeze;
                            $insert_data['addtime'] = date('Y-m-d H:i:s');
                            $insert_data['product_id'] = $oid;
                            $insert_data['event_id'] = 0;
                            db_add('points_freeze', $insert_data);
                        } elseif ($action == "submit_event_invite") {
                            $insert_data = array();
                            $insert_data['uid'] = $uid;
                            $insert_data['points'] = $points_freeze;
                            $insert_data['addtime'] = date('Y-m-d H:i:s');
                            $insert_data['product_id'] = 0;
                            $insert_data['event_id'] = $oid;
                            db_add('points_freeze', $insert_data);
                        }
                    } elseif (in_array($action, $deduct_array)) {
                        $not_enough_points = 1;
                        $operate_points = $total_points;
                        $result_points = $this->deduct_points($points_array, $total_points);
                        if ($result_points)
                            $true = 1;
                    }
                }
            }
        }

        return $true ? array('ret' => 1, 'is_points_freeze' => $is_points_freeze, 'not_enough_points' => $not_enough_points, 'operate_points' => $operate_points) : false;
    }

    function deduct_points($points_array, $points) {
        $true = 0;
        foreach ($points_array as $value) {
            if (($value['surplus_points'] - $points) >= 0) {

                db_handle('update points_detail set surplus_points=surplus_points-' . mysql_escape_string($points) . ',last_points=-' . mysql_escape_string($points) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where id=' . mysql_escape_string($value['id']));

                $true = 1;
                break;
            } else {
                $points = $points - $value['surplus_points'];
                db_handle('update points_detail set surplus_points=0 ,last_points=-' . mysql_escape_string($value['surplus_points']) . ',lastmodify="' . date('Y-m-d H:i:s') . '" where id=' . mysql_escape_string($value['id']));
            }
        }
        return $true ? true : false;
    }

    /**
     * 查詢凍結積分
     * @return   array
     */
    function get_points_freeze($uid, $oid = 0, $action = "") {
        $where = " uid=" . $uid . " and status=1";
        if ($action == 'confirm_product_invite') {
            $where .=" and product_id=" . $oid;
        } elseif ($action == 'confirm_event_invite') {
            $where .=" and event_id=" . $oid;
        }
        $param = array();
        $param['field'] = "";
        $param['where'] = $where;
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data = db_query_hash('points_freeze', $param);

        return $data['result'] ? $data['result'] : array();
    }

    /**
     * 積分過期時間
     * @return   array
     */
    function expiration_month() {
        $ret = "";
        if ((12 - intval(date('m'))) > 5) {
            $ret = date('Y-12-31 23:59:59', time());
        } else {
            $ret = date('Y-6-30 23:59:59', time() + 60 * 60 * 24 * 365);
        }
        return $ret;
    }

    /**
     * 查詢剩餘分數
     * @param    $uid 用戶id
     * @return   array
     */
    function get_points($uid) {

        $param = array();
        $param['field'] = "";
        $param['where'] = "uid=" . $uid . " and expiration_time>now() and surplus_points>0";
        $param['order'] = "settlement_time asc"; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data_points_detail = db_query_hash('points_detail', $param);

        return $data_points_detail['result'] ? $data_points_detail['result'] : array();
    }

    /**
     * 查詢今日分數
     * @param    $add :1加分，0減分，2全部
     * @param    $action 操作
     * @param    $uid 用戶id
     * @return   array
     */
    function get_today_points($uid, $action, $add = 2) {

        $where = "uid=" . $uid . " and DATEDIFF(addtime,CURDATE())=0  and action='" . $action . "'";
        $add = intval($add);
        if ($add > 2)
            return array();
        if ($add <> 2)
            $where .=" and is_add=" . $add;

        $param = array();
        $param['field'] = "";
        $param['where'] = $where;
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data = db_query_hash('points_record', $param);

        return $data['result'] ? $data['result'] : array();
    }

    /**
     * 查詢action的分數
     * @param    $action 操作
     * @param    $add :1加分，0減分，2全部
     * @return   array
     */
    function get_points_action($action = "", $is_add = 2) {

        $where = "status=1";
        if ($action)
            $where .=" and action='" . $action . "'";

        $is_add = intval($is_add);
        if ($is_add > 2)
            return array();
        if ($is_add <> 2)
            $where .=" and is_add=" . $is_add;

        //查詢action的分數 和 查詢加or減分操作
        $param = array();
        $param['field'] = "";
        $param['where'] = $where;
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data_points_action_type = db_query_hash('points_action_type', $param);

        return $data_points_action_type['result'] ? $data_points_action_type['result'] : array();
    }

    /**
     * 查詢加減分記錄
     * @param    $add :1加分，0減分，2全部
     * @param    $action 操作
     * @param    $strat_time 開始時間
     * @param    $end_time 結束時間
     * @return   array
     */
    function get_points_record($uid, $action = "", $add = 2, $strat_time = "", $end_time = "") {

        $where = " TB1.uid=" . $uid;
        $add = intval($add);
        if ($add > 2)
            return false;
        if ($add <> 2)
            $where .=" and TB1.is_add=" . $add;
        if ($action)
            $where .=" and TB1.action = '" . $action . "'";
        if ($strat_time && $end_time)
            $where .=" and TB1.addtime between '" . $strat_time . "' and '" . $end_time . "'";
        $param = array();
        $param['field'] = "TB1.*,TB2.name";
        $param['where'] = $where;
        $param['order'] = "TB1.addtime desc"; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "left join points_action_type";
        $param['on'] = "TB1.action = TB2.action";
        $data = db_query_hash('points_record', $param);

        return $data['result'] ? $data['result'] : array();
    }

    /**
     * 查詢結算分記錄
     * @param    $surplus_points :1 查詢剩餘分數大於0的
     * @param    $expiration_time ：1 查詢未過期的
     * @param    $strat_time 結算開始時間
     * @param    $end_time 結算結束時間
     * @return   array
     */
    function get_points_detail($uid, $strat_time = "", $end_time = "", $expiration_time = 0, $surplus_points = 0) {

        $where = " uid=" . $uid;

        if ($expiration_time)
            $where .=" and expiration_time>now()";
        if ($surplus_points)
            $where .=" and surplus_points>0";
        if ($strat_time && $end_time)
            $where .=" and settlement_time between '" . $strat_time . "' and '" . $end_time . "'";

        $param = array();
        $param['field'] = "";
        $param['where'] = $where;
        $param['order'] = "settlement_time desc"; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data = db_query_hash('points_detail', $param);

        return $data['result'] ? $data['result'] : array();
    }

}

?>